<?php

namespace App\Common;
use App\Models\Member\User;
use App\Models\Member\DealRecord;
use App\Models\Member\Order;
use App\Models\Member\OrderItem;
use App\Models\Member\Good;
use App\Models\Member\Store;
use App\Models\Member\TeamAward;
use App\Models\Member\BonusPoolTwo;
use App\Models\Member\TotalBonusPool;
use Config, DB;
use Log;
class PayHandler
{
    const MEMORDERTYPE = 3;// 交易记录 order_type 会员订单
    const GOLDJMTYPE = 1;// 交易记录 jm_type 余额
    const JFJMTYPE = 2;// 交易记录 jm_type 积分
    const JGZJMTYPE = 3;// 交易记录 jm_type 军功章
    const BDJMTYPE = 4;// 交易记录 jm_type 报单指数
    // 支付会员订单 - 准备信息 / 支付类型
    public static function payMemOrder($info, $type, $password)
    {
        DB::beginTransaction();
        try {
            // 会员升级
            $memGrade = self::memOrderGrade($info['order'], $info['userInfo'], $info['grade']);
            if ($memGrade['code'] != 20000) {
                return $memGrade;
            }
            //用户等级信息更新 使用新的用户信息
            $info['userInfo'] = User::where('id',$info['userInfo']['id'])->first()->toArray();
            // 订单扣款
            $memOrderDebit = self::memOrderDebit($info['order'], $info['userInfo'], $type, '', $password);
            if ($memOrderDebit['code'] != 20000) {
                return $memOrderDebit;
            }

            // 会员分享奖金发放
            $memShare = self::memOrderShare($info['order'], $info['userInfo'], $info['share']);
            if ($memShare['code'] != 20000) {
                return $memShare;
            }
            // 团队军功章发放 - 本人发放军功章 / 团队发放军功章 - 可优化 获取指定代数的用户信息可以打包为单独方法
            //将商品按照新旧报单模式对应处理团队奖励 富利指数/报单指数
            $memTeam = self::memTeamAwards($info);
            if ($memTeam['code'] != 20000) {
                return $memTeam;
            }
            // 本人积分回款
            $jfGet = self::jfGet($info['order'], $info['userInfo']);
            if ($jfGet['code'] != 20000) {
                return $jfGet;
            }

            $memModelData = self::checkModelData($info['order']['id']);
            $newModelData = $memModelData['newModelData'];
            $oldModelData = $memModelData['oldModelData'];

            if(!empty($newModelData)){
                //报单经济 报单奖 招商奖 给合伙人，二代合伙人发放 不存在则转入报单公积
                $bdPartnerResult = self::bdPartner($newModelData,$info['order'],$info['userInfo']);
                if($bdPartnerResult['code'] != 20000){
                    return $bdPartnerResult;
                }

                //虹包 奖池
                $bdMemPoolResult = self::bdMemPool($newModelData,$info['order'],$info['userInfo']);
                if($bdMemPoolResult['code'] != 20000){
                    return $bdMemPoolResult;
                }

                //分虹 奖池
                $bdOrderPoolResult = self::bdOrderPool($newModelData,$info['order'],$info['userInfo']);
                if($bdOrderPoolResult['code'] != 20000){
                    return $bdOrderPoolResult;
                }
            }

            if(!empty($oldModelData)){
                //1号奖金池金额发放 纳入1号奖金池
                $bonusPoolOne = self::bonusPoolOne($info['order'], $oldModelData);
                if($bonusPoolOne['code'] != 20000){
                    return $bonusPoolOne;
                }
                //2号奖金池包括 月度合伙人 年度合伙人 推荐合伙人 教育基金 4项奖金发放
                $teamTwo = self::bonusPoolTwo($info['order'],$info['userInfo'],$oldModelData);
                if($teamTwo['code'] != 20000){
                    return $teamTwo;
                }
            }

            // 店铺回款 会员支付 - 积分支付 - 分享发放
            $amount = (int)$info['order']['cost_price'];
            $storeGet = self::storeGet($info['order'], $amount);
            // 订单更新
            $Order = new Order;
            $updateOrder = $Order->updateMemPay($info['order']['id']);
            if ($updateOrder['code'] != 20000) {
                return $updateOrder;
            }
            DB::commit();
            return [
                'info' => '会员订单支付成功!',
                'data' => '',
                'code' => 20000
            ];
        } catch (\Exception $e) {
            DB::rollBack();
            return $e;
            return $e->getLine().$e->getMessage();
        }
    }
    //新报单模式商品 处理分虹
    public static function bdOrderPool($data,$order,$user){
        $total = 0;
        foreach ($data as $key => $value) {
            $total += $value['bd_order_pool'] * $value['goods_quantity'];
        }
        if($total > 0){
            $dealGold = [];
            $dealGold['store_id'] = $order['store_id'];
            $dealGold['status'] = 3;
            $dealGold['deal_item_id'] = $order['id'];
            $dealGold['deal_user_id'] = $user['id'];
            $dealGold['deal_get_id'] = $user['team_id'];
            $dealGold['partner_time'] = $user['team_id'] != 0 ? User::where('id',$user['team_id'])->first()->partner_at : NULL;
            $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
            $dealGold['jm_type'] = self::GOLDJMTYPE;// 金额
            $dealGold['mark'] = 0;
            $dealGold['user_id'] = 1;
            $dealGold['grade'] = 0;
            $dealGold['reason'] = '纳入分虹';
            $dealGold['deal_type'] = 59;// 分虹
            $dealGold['amount'] = $total;
            $dealRecord = new DealRecord;
            $goldReturned = $dealRecord->returnedMoney($dealGold,9);
            if ($goldReturned['code'] != 20000) {
                return $goldReturned;
            }
        }
        return [
            'info' => '分虹发放完毕!',
            'data' => '',
            'code' => 20000
        ];
    }
    //新报单模式商品 处理虹包
    public static function bdMemPool($data,$order,$user){
        $total = 0;
        foreach ($data as $key => $value) {
            $total += $value['bd_member_pool'] * $value['goods_quantity'];
        }
        if($total > 0){
            $dealGold = [];
            $dealGold['store_id'] = $order['store_id'];
            $dealGold['status'] = 3;
            $dealGold['deal_item_id'] = $order['id'];
            $dealGold['deal_user_id'] = $user['id'];
            $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
            $dealGold['jm_type'] = self::GOLDJMTYPE;// 金额
            $dealGold['mark'] = 0;
            $dealGold['user_id'] = 1;
            $dealGold['grade'] = 0;
            $dealGold['reason'] = '纳入虹包';
            $dealGold['deal_type'] = 56;// 
            $dealGold['amount'] = $total;
            $dealRecord = new DealRecord;
            $goldReturned = $dealRecord->returnedMoney($dealGold,8);
            if ($goldReturned['code'] != 20000) {
                return $goldReturned;
            }
        }
        return [
            'info' => '虹包发放完毕!',
            'data' => '',
            'code' => 20000
        ];
    }
    //新报单模式商品 处理报单奖 给合伙人一代，二代发放 没有则转入报单公积
    public static function bdPartner($newModelData,$order,$user){
        $partner_one = 0; 
        $partner_two = 0; 
        foreach($newModelData as $k => $v){
            $partner_one += $v['bd_partner_one'] * $v['goods_quantity'];
            $partner_two += $v['bd_partner_two'] * $v['goods_quantity'];
        }
        $dealGold = [];
        $dealGold['store_id'] = $order['store_id'];
        $dealGold['status'] = 3;
        $dealGold['deal_item_id'] = $order['id'];
        $dealGold['deal_user_id'] = $user['id'];
        $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
        $dealGold['jm_type'] = self::GOLDJMTYPE;// 金额
        $dealGold['mark'] = 0;
        $DealRecord = new DealRecord;
        if($partner_one > 0){
            $dealGold['amount'] = $partner_one;
            if($user['team_id'] > 0){
                $teamInfo = User::where('id',$user['team_id'])->first()->toArray();
                
                $dealGold['user_id'] = $user['team_id'];//一代合伙人获取
                $dealGold['grade'] = $teamInfo['grade'];
                $dealGold['reason'] = '下级会员订货获取报单奖';
                $dealGold['deal_type'] = 54;// 报单经济
                $goldReturned = $DealRecord->returnedMoney($dealGold);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
            }else{
                $dealGold['user_id'] = 1;
                $dealGold['grade'] = 0;
                $dealGold['reason'] = '报单奖转入报单公积';
                $dealGold['deal_type'] = 55;// 报单经济
                $goldReturned = $DealRecord->returnedMoney($dealGold,7);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
            }
        }
        if($partner_two > 0){
            $dealGold['amount'] = $partner_two;
            if($user['recom_id'] > 0){
                $recomInfo = User::where('id',$user['recom_id'])->first()->toArray();
                
                $dealGold['user_id'] = $user['recom_id'];//二代合伙人获取
                $dealGold['grade'] = $recomInfo['grade'];
                $dealGold['reason'] = '下级会员订货获取招商奖';
                $dealGold['deal_type'] = 54;// 报单经济
                $goldReturned = $DealRecord->returnedMoney($dealGold);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
            }else{
                $dealGold['user_id'] = 1;
                $dealGold['grade'] = 0;
                $dealGold['reason'] = '招商奖转入报单公积';
                $dealGold['deal_type'] = 55;// 报单经济
                $goldReturned = $DealRecord->returnedMoney($dealGold,7);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
            }
        }
        return [
            'info' => '报单经济发放完毕!',
            'data' => '',
            'code' => 20000
        ];
    }

    //订单支付 验证商品为新旧报单模式并作出相应处理  0为新模式 1为旧模式 0：发放报单指数 1:发放富利指数
    public static function memTeamAwards($info){
        $dealRecord = new DealRecord;
        $result = self::checkModelData($info['order']['id']);
        $newModelData = $result['newModelData'];
        $oldModelData = $result['oldModelData'];
        if(!empty($newModelData)){
            //店铺团队奖励名称
            $awardName = $info['teamAward']['bd_award_name']; 
            $allAward = 0;
            foreach ($newModelData as $key => $value) {
                $allAward += $value['bd_index'] * $value['goods_quantity'];
            }
            if($allAward > 0){
                $dealGold = [];
                $dealGold['store_id'] = $info['order']['store_id'];
                $dealGold['status'] = 3;
                $dealGold['deal_item_id'] = $info['order']['id'];
                $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
                $dealGold['jm_type'] = self::BDJMTYPE;// 报单指数
                $dealGold['user_id'] = $info['userInfo']['id'];
                $dealGold['grade'] = $info['userInfo']['grade'];
                $dealGold['mark'] = 0;
                $dealGold['amount'] = $allAward;
                $dealGold['reason'] = '会员订货获取'.$awardName;
                $dealGold['deal_type'] = 44;// 会员订货获取报单指数
                $goldReturned = $dealRecord->returnedMoney($dealGold);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
    
                $memTeam = self::memOrderTeam($info['order'], $info['userInfo'], $info['teamAward'], $allAward,0);
                if ($memTeam['code'] != 20000) {
                    return $memTeam;
                }
            }
        }
        if(!empty($oldModelData)){
            //店铺团队奖励名称
            $awardName = $info['teamAward']['award_name']; 
            $allAward = 0;
            foreach ($oldModelData as $key => $value) {
                $allAward += $value['jgz'] * $value['goods_quantity'];
            }
            $goods = new Good;
            if($allAward > 0){
                $dealGold = [];
                $dealGold['store_id'] = $info['order']['store_id'];
                $dealGold['status'] = 3;
                $dealGold['deal_item_id'] = $info['order']['id'];
                $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
                $dealGold['jm_type'] = self::JGZJMTYPE;// 军功章
                $dealGold['user_id'] = $info['userInfo']['id'];
                $dealGold['grade'] = $info['userInfo']['grade'];
                $dealGold['mark'] = 0;
                $dealGold['amount'] = $allAward;
                $dealGold['reason'] = '会员订货获取'.$awardName;
                $dealGold['deal_type'] = 17;// 会员订货获取军功章
                $goldReturned = $dealRecord->returnedMoney($dealGold);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
    
                $memTeam = self::memOrderTeam($info['order'], $info['userInfo'], $info['teamAward'], $allAward,1);
                if ($memTeam['code'] != 20000) {
                    return $memTeam;
                }
            }
        }
        return [
            'info' => '团队奖励发放完毕!',
            'data' => '',
            'code' => 20000
        ];
    } 
    //将订单商品详情按照商品的新旧报单模式分组
    public static function checkModelData($orderId){
        $result = [];
        $orderitem = new OrderItem;
        $items = $orderitem->join('goods as g', 'order_items.good_id', '=', 'g.id')
        ->where("order_items.order_id",$orderId)
        ->select('g.id as goods_id', 'order_items.id as order_items_id', 'g.bonus_pool_one', 'g.jgz', 'order_items.goods_quantity',
        'g.bd_index','g.new_model','g.is_loop','g.arr_loop','g.added','g.bd_partner_one','g.bd_partner_two','g.bd_member_pool','g.bd_order_pool')
        ->get()->toArray();

        $newModelData = array_filter($items, function ($item){
            return $item['new_model'] == 0;
        });
        $oldModelData = array_filter($items, function ($item){
            return $item['new_model'] == 1;
        });
        $result['newModelData'] = $newModelData;
        $result['oldModelData'] = $oldModelData;
        return $result;
    }

    // 店铺回款 = 会员支付 - 积分支付 - 分享发放
    public static function storeGet($order, $amount)
    {
        $DealRecord = new DealRecord;
        $dealGold = [];
        $dealGold['store_id'] = $order['store_id'];
        $dealGold['status'] = 3;
        $dealGold['deal_item_id'] = $order['id'];
        $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
        $dealGold['jm_type'] = self::GOLDJMTYPE;
        $dealGold['user_id'] = 1;
        $dealGold['grade'] = 0;
        $dealGold['mark'] = 0;
        $dealGold['amount'] = $amount;
        $dealGold['reason'] = '店铺回款';
        $dealGold['deal_type'] = 9;
        $goldReturned = $DealRecord->returnedMoney($dealGold);
        if ($goldReturned['code'] != 20000) {
            return $goldReturned;
        }
        return [
            'info' => '店铺回款成功!',
            'data' => '',
            'code' => 20000
        ];
    }
    // 积分回款
    public static function jfGet($order, $user)
    {
        // if ($order['store_id'] == 21) {
            // $jf = $order['pay_price'] - $order['jf_price'];
        // } else {
            $jf = $order['jf'];
        // }
        
        if ($order['jf'] > 0) {
            $DealRecord = new DealRecord;
            $dealGold = [];
            $dealGold['store_id'] = $order['store_id'];
            $dealGold['status'] = 3;
            $dealGold['deal_item_id'] = $order['id'];
            $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
            $dealGold['jm_type'] = self::JFJMTYPE;
            $dealGold['user_id'] = $user['id'];
            $dealGold['grade'] = $user['grade'];
            $dealGold['mark'] = 0;
            $dealGold['amount'] = $jf;
            $dealGold['reason'] = '会员订货本人获取积分';
            $dealGold['deal_type'] = 14;// 
            $goldDeduct = $DealRecord->returnedMoney($dealGold);
            if ($goldDeduct['code'] != 20000) {
                return $goldDeduct;
            }
        }
        return [
            'info' => '会员订单使用积分成功!',
            'data' => '',
            'code' => 20000
        ];
    }

    // 会员订单订单扣款
    private static function memOrderDebit($order, $userInfo, $type, $mark = '', $password)
    {
        $DealRecord = new DealRecord;
        $dealGold = [];
        if ($type == 1) {
            // 余额支付
            $dealGold['store_id'] = $order['store_id'];
            $dealGold['user_id'] = $order['user_id'];
            $dealGold['status'] = 1;
            $dealGold['reason'] = '会员订单支付成功';
            $dealGold['deal_item_id'] = $order['id'];
            $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
            $dealGold['grade'] = $userInfo['grade'];
            $dealGold['mark'] = $mark;

            $dealGold['deal_type'] = 6;// 会员支付订单
            $dealGold['jm_type'] = self::GOLDJMTYPE;// 余额
            $dealGold['amount'] = $order['pay_price'] - $order['jf_price'] - $order['express_price']*100;// 支付金额
            $dealGold['last_balance'] = $userInfo['gold'];// 会员余额
            // 金额扣除
            $goldDeduct = $DealRecord->deductMoney($dealGold);
            if ($goldDeduct['code'] != 20000) {
                return $goldDeduct;
            }
            // 判断是否使用积分, 并根据情况调用积分扣款, 改变余额实际支付数目
            if ($order['jf_price'] != 0) {
                $store = new Store;
                $storeInfo = $store->where('id',$order['store_id'])->first();
                $dealGold['deal_type'] = 16;// 会员订单使用积分
                $dealGold['jm_type'] = self::JFJMTYPE;// 积分
                $dealGold['amount'] = $order['jf_price']*$storeInfo['ratio'];
                $dealGold['last_balance'] = $userInfo['jf'];// 会员积分
                $jfDeduct = $DealRecord->deductMoney($dealGold);
                if ($jfDeduct['code'] != 20000) {
                    return $jfDeduct;
                }
            }
            return [
                'info' => '会员订单余额扣款成功!',
                'data' => '',
                'code' => 20000
            ];
        } else {
            // 微信支付扣款逻辑 - 判断是否支付成功, 如果成功则返回成功
            $result = $DealRecord->where('pay_orderid',$password)->update(['status'=>1,'grade'=>$userInfo['grade']]);
            // 判断是否使用积分, 并根据情况调用积分扣款, 改变余额实际支付数目
            if ($order['jf_price'] != 0) {
                $store = new Store;
                $storeInfo = $store->where('id',$order['store_id'])->first();
                $dealGold['store_id'] = $order['store_id'];
                $dealGold['user_id'] = $order['user_id'];
                $dealGold['status'] = 1;
                $dealGold['reason'] = '会员订单积分抵扣扣除';
                $dealGold['deal_item_id'] = $order['id'];
                $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
                $dealGold['grade'] = $userInfo['grade'];
                $dealGold['mark'] = $mark;

                $dealGold['deal_type'] = 16;// 会员订单使用积分
                $dealGold['jm_type'] = self::JFJMTYPE;// 积分
                $dealGold['amount'] = $order['jf_price']*$storeInfo['ratio'];
                $dealGold['last_balance'] = $userInfo['jf'];// 会员积分
                $jfDeduct = $DealRecord->deductMoney($dealGold);
                if ($jfDeduct['code'] != 20000) {
                    return $jfDeduct;
                }
            }
            if($result){
                return [
                    'info' => '会员订单微信扣款成功!',
                    'data' => '',
                    'code' => 20000
                ];
            }else{
                return [
                    'info' => '会员订单微信扣款失败!',
                    'data' => '',
                    'code' => 20001
                ];
            }
        }
    }

    private static function memOrderGrade($order, $userInfo, $grade)
    {
        // 如果是美康宝店铺，则升级条件全部按照历史获得积分来
        $storeId = $userInfo['store_id'];
        $sum = Order::where('user_id', $userInfo['id'])->whereIn('order_status', [3,4,5])->sum('base_price') ? : 0;
        $jfNumAll = ($sum + $order['base_price'])*100;

        //合伙人等级信息
        $arr = $grade[0];
        //到了升级合伙人的等级时 是另外一套升级要求
        if  ($userInfo['grade'] + 1 >= $arr['level']){
            $result = self::copartner($userInfo,$arr);
            return $result;
        }
        //非合伙人等级升级
        array_shift($grade);
        foreach ($grade as $key => $value) {
            if ($value['level'] == $userInfo['grade']) {
                break;
            }
            if ($jfNumAll >= $value['jf_num']) {
                $recommend = json_decode($value['recommend'], 1);
                $data = self::checkRecommend($userInfo, $recommend, $value['level'], $value['jf'], $order['jf']);
                if ($data['code'] != 20000) {
                    return $data;
                }
                break;
            }
            continue;
        }
        return [
            'info' => '无需升级!',
            'data' => '',
            'code' => 20000
        ];
    }
    // 判断是否符合推荐标准
    public static function checkRecommend($userInfo, $recommend, $grade, $jf, $order)
    {
        if ($recommend['num'] != 0) {
            $numRecommend = User::where('left', '>', $userInfo['left'])->where('right', '<', $userInfo['right'])->where('grade', $recommend['grade'])->count();
            if ($numRecommend < $recommend['num']) {
                return [
                    'info' => '不满足推荐要求!',
                    'data' => '',
                    'code' => 20000
                ];
            }
        }

        //历史累计积分要求
        $DealRecord = new DealRecord;
        $sum = $DealRecord->where('store_id', $userInfo['store_id'])
        ->where('user_id', $userInfo['id'])
        ->where('jm_type', 2)
        ->where('status', 3)
        ->sum('amount');
        $jfNumAll = $sum + $order;

        if($jfNumAll < $jf){
            return [
                'info' => '不满足历史累计积分要求',
                'data' => $jfNumAll/100,
                'code' => 20000
            ];
        }

        // 无推荐条件 或 满足推荐条件 , 进行等级变更
        $recommendUser = User::where('id', $userInfo['id'])->update(['grade' => $grade,'grade_at'=>date('Y-m-d H:i:s')]);
        if ($recommendUser) {
            return [
                'info' => '满足推荐要求!',
                'data' => $grade,
                'code' => 20000
            ];
        } else {
            return [
                'info' => '升级失败!',
                'data' => $grade,
                'code' => 20001
            ];
        }
    }
    //支付订单处理分享经济
    public static function memOrderShare($order, $userInfo, $share)
    {
        // 获取推荐人信息 - 级数 / 身份
        $refer = User::where('left', '<', $userInfo['left'])
        ->where('right', '>', $userInfo['right'])
        ->where('id', '!=', 1)
        ->orderBy('level','desc')
        ->limit($share['num'])
        ->select('id', 'grade', 'level')
        ->get()->toArray();
        // $refer = array_slice($refer, 0, $share['num']);
        
        // 计算 分配本金 => 本金 / 利润 / 商品
        $iniGold = self::shareIniGold($order, $share['type'],$order['id']);
        Log::info("分享本金:".$iniGold);
        if($iniGold == 0){
            return [
                'info' => '分享金额为0，无需发放!',
                'data' => $iniGold,
                'code' => 20000
            ];
        }
        $result = self::checkModelData($order['id']);
        $newModelData = $result['newModelData'];
        $oldModelData = $result['oldModelData'];
        $newResult = self::newModelGoodsShare($order, $userInfo, $share,$refer,$newModelData,$iniGold);
        if ($newResult['code'] != 20000) {
            return $newResult;
        }
        $oldResult = self::oldModelGoodsShare($order, $userInfo, $share,$refer,$oldModelData,$iniGold);
        if ($oldResult['code'] != 20000) {
            return $oldResult;
        }
        return [
            'info' => '发放成功!',
            'data' => 1,
            'code' => 20000
        ];
    }
    //存在新报单模式商品 处理分享经济
    private static function newModelGoodsShare($order, $userInfo, $share,$refer,$newModelData,$iniGold){
            if(!empty($newModelData)){
                $orderItemsId = array_column($newModelData,'order_items_id');
                // 获取分配方式 - 传递 分配方式 / 分配比例 / 推荐人信息  , 遍历发放
                $deal = new DealRecord;
                $goldSend = 0;
                $dealGold = [];
                $dealGold['store_id'] = $order['store_id'];
                $dealGold['deal_item_id'] = $order['id'];
                $dealGold['deal_user_id'] = $userInfo['id'];
                $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
                $dealGold['jm_type'] = self::GOLDJMTYPE;
                if (!empty($refer)) {
                    // 移除并获取数组中的第一个元素
                    $firstItem = $refer[0];
                    $mem = User::where('pid', $firstItem['id'])
                            ->select('id', 'grade', 'level')
                            ->get()->toArray();

                    $memId = array_column($mem,'id');
                    $memOrderCount = Order::where('store_id',$order['store_id'])->whereIn('user_id',$memId)->whereIn('order_status',[3,4,5])->count();
                    $memCount = $memOrderCount + 1;
                    $memSum = 0;//新报单模式直推金额
                    foreach($newModelData as $k => $v){
                        $arr_loop = json_decode($v['arr_loop'],1);
                        $arr_loop_count = count($arr_loop);
                        if($v['is_loop'] == 1){
                            $memSum += ($memCount > $arr_loop_count ? $v['added'] : $arr_loop[$memCount]) * $v['goods_quantity'];
                        }else{
                            $cycle = ($memCount - 1) % $arr_loop_count + 1;
                            $memSum += $arr_loop[$cycle] * $v['goods_quantity'];
                        }
                    }
                
                    $aboveMem = $refer[0];
                    $dai = $userInfo['level'] - $aboveMem['level'];
                    $radio = json_decode($share['radio'], 1);
                    if($dai == 1){
                        $dealGold['status'] = 3;
                        $dealGold['user_id'] = 1;
                        $dealGold['grade'] =  0;
                        $dealGold['reason'] = '码上折转入码上返';
                        $dealGold['mark'] = '';
                        $dealGold['deal_type'] = 46;// 纳入码上返
                        $dealGold['amount'] = self::shareSend($iniGold, $share['method'], $radio, $dai ,$aboveMem['grade'],$share['type'],$orderItemsId);
                        // 金额增加 并 计算总计发放
                        
                        $goldReturned = $deal->returnedMoney($dealGold,6);
                        if ($goldReturned['code'] != 20000) {
                            return $goldReturned;
                        }
                        
                        if($memSum > 0 ){
                            $dealGold['status'] = 1;
                            $dealGold['user_id'] = 1;//直推池子扣除 发放给直推用户
                            $dealGold['grade'] = 0;
                            $dealGold['reason'] = '码上返扣除';
                            $dealGold['mark'] = '码上返扣除,直推用户'.$aboveMem['id'].'已有直推报单数为'.$memCount.'单';
                            $dealGold['deal_type'] = 47;//码上返扣除
                            $dealGold['amount'] = $memSum;
                            $referrerResult = $deal->deductMoney($dealGold,6);
                            if ($referrerResult['code'] != 20000) {
                                return $referrerResult;
                            }
                            
                            $dealGold['status'] = 3;
                            $dealGold['user_id'] = $aboveMem['id'];//直推池子扣除 发放给直推用户
                            $dealGold['grade'] = $aboveMem['grade'];
                            $dealGold['reason'] = '码上返发放';
                            $dealGold['mark'] = '码上返发放,已有直推报单数为'.$memCount.'单';
                            $dealGold['deal_type'] = 53;//码上返发放
                            $dealGold['amount'] = $memSum;

                            $grantResult = $deal->returnedMoney($dealGold);
                            if ($grantResult['code'] != 20000) {
                                return $grantResult;
                            }
                        }
                    }


                    foreach ($refer as $key => $value) {
                        if($key > 0){
                            $dai = $userInfo['level'] - $value['level'];
                            $dealGold['user_id'] = $value['id'];
                            $dealGold['grade'] = $value['grade'];
                            $dealGold['reason'] = '报单折上折';
                            $dealGold['mark'] = $dai;
                            $dealGold['amount'] = self::shareSend($iniGold, $share['method'], $radio, $dai ,$value['grade'],$share['type'],$orderItemsId);
                            // 金额增加 并 计算总计发放
                            $indirectResult = $deal->returnedMoney($dealGold);
                            if ($indirectResult['code'] != 20000) {
                                return $indirectResult;
                            }
                        }
                        $goldSend += $dealGold['amount'];
                    }
                }
                //有分享奖金未发放 则转入1号奖金池
                if (count($refer) < $share['num']) {
                    $shareResult = self::ShareInPool(count($refer),$share,$order,$orderItemsId,0);
                    if ($shareResult['code'] != 20000) {
                        return $shareResult;
                    }
                }
            }
            return [
                'info' => '发放成功!',
                'data' => 1,
                'code' => 20000
            ];
    }
    //存在旧报单模式商品 处理分享经济
    private static function oldModelGoodsShare($order, $userInfo, $share,$refer,$oldModelData,$iniGold){
        if(!empty($oldModelData)){
            $orderItemsId = array_column($oldModelData,'order_items_id');
            // 获取分配方式 - 传递 分配方式 / 分配比例 / 推荐人信息  , 遍历发放
            $dealRecord = new DealRecord;
            $goldSend = 0;
            $dealGold = [];
            $dealGold['store_id'] = $order['store_id'];
            $dealGold['status'] = 3;
            $dealGold['deal_item_id'] = $order['id'];
            $dealGold['deal_user_id'] = $userInfo['id'];
            $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
            $dealGold['deal_type'] = 7;// 分享奖金
            $dealGold['jm_type'] = self::GOLDJMTYPE;
            foreach ($refer as $key => $value) {
                $dai = $userInfo['level'] - $value['level'];
                $radio = json_decode($share['radio'], 1);
                $dealGold['user_id'] = $value['id'];
                $dealGold['grade'] = $value['grade'];
                $dealGold['reason'] = $dai == 1 ? '码上折' : '折上折';
                $dealGold['mark'] = $dai;
                $dealGold['amount'] = self::shareSend($iniGold, $share['method'], $radio, $dai ,$value['grade'],$share['type'],$orderItemsId);
                // 金额增加 并 计算总计发放
                $goldReturned = $dealRecord->returnedMoney($dealGold);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
                $goldSend += $dealGold['amount'];
            }
            //有分享奖金未发放 则转入1号奖金池
            if (count($refer) < $share['num']) {
                $shareResult = self::ShareInPool(count($refer),$share,$order,$orderItemsId,1);
                if ($shareResult['code'] != 20000) {
                    return $shareResult;
                }
            }
        }
        return [
            'info' => '发放成功!',
            'data' => 1,
            'code' => 20000
        ];
    }
    // 根据 本金类型 获取 本金数额 - 本金方式 / 订单信息( ID / 支付价 / 成本价 )
    private static function shareIniGold($order, $type,$orderId)
    {
        $iniGold = 0;
        switch ($type) {
            case 1:
                # 本金 - 现在变为实际支付
                $iniGold = $order['pay_price'] - $order['jf_price'];
                break;
            case 2:
                # 利润
                $iniGold = $order['pay_price'] - $order['cost_price'];
                break;
            case 3:
                # 商品
                $OrderItem = new OrderItem;
                $iniGold = $OrderItem->getShareGold($orderId);
                break;
            default:
                # code...
                break;
        }
        return $iniGold;
    }

    // 分配金额 / 分配方式 / 分配比例 / 关系 / 身份 
    private static function shareSend($iniGold, $method, $radio, $dai, $grade = 0, $type, $orderItemsId)
    {
        $goldBack = 0;
        switch ($method) {
            case 1:
                # 关系
                if($type == 3){
                    $orderitem = new OrderItem;
                    $goldBack = $orderitem->shareLevelGold($orderItemsId,$dai);
                }else{
                    $goldBack = $iniGold * $radio[$dai];//分配金额*分配比例
                }
                break;
            case 2:
                # 身份
                $goldBack = $iniGold * $radio[$grade];
                break;    
            case 3:
                # 关系 + 身份
                $key = $dai.'-'.$grade;
                $goldBack = $iniGold * $radio[$key];
                break;        
            default:
                # code...
                break;
        }
        return $goldBack;
    }

    public static function memOrderTeam($order, $userInfo, $team, $allAward,$type)
    {
        // N级内 需要发放的总军功章 订单实际支付价
        // $allAward = ($order['pay_price'] - $order['jf_price']) * ($team['n_inner']/100);
        //订单中商品富利指数总和

        if($type == 1){
            $limit = $team['division_num'] + $team['rela_num'];
            $teamName = $team['award_name'];
            $jm_type = self::JGZJMTYPE;
            $radio = json_decode($team['radio_inner'], 1);
            $radio_outer = $team['radio_outer']/100;
            $divisionNum = $team['division_num'];
            $in_deal_type = 18; 
            $out_deal_type = 19; 
        }else{
            $limit = $team['bd_division_num'];
            $teamName = $team['bd_award_name'];
            $jm_type = self::BDJMTYPE;
            $radio = json_decode($team['bd_radio_inner'], 1);
            $radio_outer = 0;
            $divisionNum = $team['bd_division_num'];
            $in_deal_type = 45; 
            $out_deal_type = 45;
        }

        // N级 + N级外代数 需要发放的用户信息
        $refer = User::where('left', '<', $userInfo['left'])
        ->where('right', '>', $userInfo['right'])
        ->where('id', '!=', 1)
        ->orderBy('level', 'desc')
        ->limit($limit)
        ->select('id', 'grade', 'level')
        ->get()->toArray();
        if (empty($refer)) {
            return [
                'info' => '无需发放'.$teamName.'!',
                'data' => '',
                'code' => 20000
            ];
        }
        // 遍历用户信息 , 先发放N级用户 及对应比例的军功章 , 
        $DealRecord = new DealRecord;
        $dealGold = [];
        $dealGold['store_id'] = $order['store_id'];
        $dealGold['status'] = 3;
        $dealGold['deal_item_id'] = $order['id'];
        $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
        $dealGold['jm_type'] = $jm_type;// 军功章/报单指数
        foreach ($refer as $key => $value) {
            $dai = $userInfo['level'] - $value['level'];
            $dealGold['user_id'] = $value['id'];
            $dealGold['grade'] = $value['grade'];
            $dealGold['mark'] = $dai;
            if ($dai <= $divisionNum) {
                $dealGold['amount'] = $allAward * $radio[$dai];
                $dealGold['reason'] = '[第 '.$dai.' 代]'.$teamName.'获得';
                $dealGold['deal_type'] = $in_deal_type;// 分享奖金
            } else {
                $dealGold['amount'] = $allAward * $radio_outer;
                $dealGold['reason'] = '[第 '.$dai.' 代]'.$teamName.'分享';
                $dealGold['deal_type'] = $out_deal_type;// 分享奖金
            }
            // 金额增加 并 计算总计发放
            $goldReturned = $DealRecord->returnedMoney($dealGold);
            if ($goldReturned['code'] != 20000) {
                return $goldReturned;
            }
        }
        return [
            'info' => $team['award_name'].'发放成功!',
            'data' => '',
            'code' => 20000
        ];
    }

    public static function bonusPoolOne($order, $items){
        $sum = 0;
        foreach ($items as $key => $value) {
            $sum += $value['bonus_pool_one'] * $value['goods_quantity'];
        }
        if($sum > 0){
            $DealRecord = new DealRecord;
            $dealGold = [];
            $dealGold['store_id'] = $order['store_id'];
            $dealGold['status'] = 3;
            $dealGold['deal_item_id'] = $order['id'];
            $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
            $dealGold['jm_type'] = self::GOLDJMTYPE;// 余额
            $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
            $dealGold['grade'] = 0;
            $dealGold['mark'] = 0;
            $dealGold['amount'] = $sum;
            $dealGold['reason'] = '纳入会员折扣';
            $dealGold['deal_type'] = 21;// 会员订货获取军功章
            $goldReturned = $DealRecord->returnedMoney($dealGold, 1);
            if ($goldReturned['code'] != 20000) {
                return $goldReturned;
            }
        }
        return [
            'info' => '纳入会员折扣成功!',
            'data' => $sum,
            'code' => 20000
        ];
    }

    public static function bonusPoolTwo($order,$user,$oldModelData){
        $orderItemsId = array_column($oldModelData,'order_items_id');
        $orderItem = new OrderItem;
        $dealRecord = new DealRecord;
        $bonusPoolTwo = new bonusPoolTwo;
        $goodsData = $orderItem->join('bonus_pool_twos as b', 'order_items.good_id', '=', 'b.good_id')
        ->whereIn('order_items.id',$orderItemsId)
        ->select('b.good_id', 'b.bonus_pool_two', 'b.team_month', 'b.team_year', 'b.team_recommend', 'b.team_fund', 'order_items.goods_quantity')
        ->get()->toArray();
        $arr = [];
        $bonus_pool_two = 0;
        $arr['team_month_sum'] = 0;
        $arr['team_year_sum'] = 0;
        $arr['team_recommend_sum'] = 0;
        $arr['team_fund_sum'] = 0;
        foreach ($goodsData as $key => $value) {
            $bonus_pool_two += $value['bonus_pool_two']*$value['goods_quantity'];
            $arr['team_month_sum'] += $value['team_month']*$value['goods_quantity'];
            $arr['team_year_sum'] += $value['team_year']*$value['goods_quantity'];
            $arr['team_recommend_sum'] += $value['team_recommend']*$value['goods_quantity'];
            $arr['team_fund_sum'] += $value['team_fund']*$value['goods_quantity'];
        }
        if($bonus_pool_two != $arr['team_month_sum'] + $arr['team_year_sum'] + $arr['team_recommend_sum'] + $arr['team_fund_sum']){
            return [
                'info' => '合伙人折扣分配比例不达标!',
                'data' => $arr['bonus_pool_two'],
                'code' => 20001
            ];
        }
        //如果用户使用积分抵扣 则从教育培训基金中扣除
        if($order['jf_price'] > 0){
            $arr['team_fund_sum'] = $arr['team_fund_sum'] - $order['jf_price'];
        }

        $total = new TotalBonusPool;
        foreach ($arr as $key => $value) {
            $info = $total->getKeyText($key);
            if($info['type'] == 2){
                $deal_get_id = $user['team_id'];
            }else if($info['type'] == 4){
                $deal_get_id = $user['recom_id'];
            }else{
                $deal_get_id = 0;
            }
             

            if($value > 0){
                $dealGold = [];
                $dealGold['store_id'] = $order['store_id'];
                $dealGold['status'] = 3;
                $dealGold['deal_item_id'] = $order['id'];
                $dealGold['deal_user_id'] = $order['user_id'];
                $dealGold['deal_get_id'] = $deal_get_id;
                $dealGold['partner_time'] = $deal_get_id != 0 ? User::where('id',$deal_get_id)->first()->partner_at : NULL;
                $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
                $dealGold['jm_type'] = self::GOLDJMTYPE;// 余额
                $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
                $dealGold['grade'] = 0;
                $dealGold['mark'] = 0;
                $dealGold['amount'] = $value;
                $dealGold['reason'] = $info['reason'].'收入';
                $dealGold['deal_type'] = $info['deal_type'];
                $goldReturned = $dealRecord->returnedMoney($dealGold, $info['type']);
                if ($goldReturned['code'] != 20000) {
                    return $goldReturned;
                }
            }
        }
        return [
            'info' => '合伙人折扣发放成功!',
            'data' => $bonus_pool_two,
            'code' => 20000
        ];
        
    } 

    //检测升级为合伙人
    public static function copartner($userInfo,$grade){
        $user = new User;
        $order = new Order;

        if($grade['copartner'] != 1){
            return [
                'info' => '合伙人升级标准选择有误',
                'data' => $grade,
                'code' => 20000
            ];
        }
        //直推人数要求
        $directNum = $user->directNum($userInfo);
        if($directNum < $grade['direct_num']){
            return [
                'info' => '直推人数未达到合伙人要求',
                'data' => $directNum,
                'code' => 20000
            ];
        }

        //团队人数要求
        $teamNum = $user->teamNum($userInfo);
        if($teamNum < $grade['team_num']){
            return [
                'info' => '团队人数未达到合伙人要求',
                'data' => $teamNum,
                'code' => 20000
            ];
        }

        //团队销售额
        $teamSales = $order->teamSales($userInfo)*100;
        if($teamSales < $grade['team_sales']){
            return [
                'info' => '团队销售额未达到合伙人要求',
                'data' => $teamSales,
                'code' => 20000
            ];
        }
        
         // 无推荐条件 或 满足推荐条件 , 进行等级变更  暂不进行变更 升级合伙人需向公司申请，后台管理员操作升级 
        //  $recommendUser = User::where('id', $userInfo['id'])->update(['grade' => $grade['level']]);
        //  if ($recommendUser) {
            return [
                'info' => '满足升级要求',
                'data' => $grade,
                'code' => 20000
            ];
        //  } else {
            // return [
            //     'info' => '升级失败',
            //     'data' => $grade,
            //     'code' => 20001
            // ];
        //  }
    } 

    //分享经济未发放的部分 计入1号奖金池
    public static function shareInPool($count,$share,$order,$orderItemsId,$type){
        $num = $share['num'];
        $gold = self::shareIniGold($order, $share['type'],$orderItemsId);
        $orderitem = new OrderItem;
        $DealRecord = new DealRecord;
        $dealGold = [];
        $dealGold['store_id'] = $order['store_id'];
        $dealGold['status'] = 3;
        $dealGold['deal_item_id'] = $order['id'];
        $dealGold['order_type'] = self::MEMORDERTYPE;// 会员订单
        $dealGold['jm_type'] = self::GOLDJMTYPE;// 余额
        $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
        $dealGold['grade'] = 0;
        $dealGold['mark'] = $type == 1 ? '码上折，折上折全部转入会员折扣' : '码上折，折上折全部转入报单公积';
        $dealGold['amount'] = $gold;
        $dealGold['reason'] = $type == 1 ? '码上折，折上折全部转入会员折扣' : '码上折，折上折全部转入报单公积';
        $dealGold['deal_type'] = $type == 1 ? 30 : 51;// 分享经济转入1号奖金池/报单公积
        
        if($count == 0 && $gold > 0){
            $goldReturned = $type == 1 ? $DealRecord->returnedMoney($dealGold, 1) : $DealRecord->returnedMoney($dealGold, 7);
            return $goldReturned;
        }

        $i = $count+1;
        $goldBack = 0;
        for ($i; $i <= $num; $i++) { 
            $goldBack += $orderitem->shareLevelGold($orderItemsId,$i);
        }
        
        $dealGold['reason'] = $type == 1 ? '折上折转入会员折扣' : '折上折转入报单公积';
        $dealGold['mark'] = $type == 1 ? '折上折转入会员折扣' : '折上折转入报单公积';
        $dealGold['amount'] = $goldBack;
        if($goldBack > 0){
            $goldReturned = $type == 1 ? $DealRecord->returnedMoney($dealGold, 1) : $DealRecord->returnedMoney($dealGold, 7);
            return $goldReturned;
        }
        return [
            'info' => '分享经济发放完毕',
            'data' => $dealGold,
            'code' => 20000
        ];
    }
}